package cn.wenhe9.controller;

import cn.wenhe9.domain.Customer;
import cn.wenhe9.service.CustomerService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerService service;
    @Autowired
    private ObjectMapper mapper;

    @RequestMapping("/findAll")
    @ResponseBody
    public ModelAndView findAll(int pageNum, Customer customer) throws JsonProcessingException {

        ModelAndView modelAndView = new ModelAndView();
        PageHelper.startPage(pageNum, 10);
        modelAndView.setViewName("customer");

        PageInfo<Customer> pageInfo = new PageInfo<>(service.findAll(customer));
        modelAndView.addObject("pages", pageInfo);
        modelAndView.addObject("writeBack", customer);
        modelAndView.addObject("source", service.findSource());
        modelAndView.addObject("job", service.findJob());
        modelAndView.addObject("level", service.findLevel());

        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/create")
    public String createCustomer(Customer customer){
        return service.create(customer);
    }

    @ResponseBody
    @RequestMapping("/delete")
    public String deleteCustomer(int cust_id){
        return service.delete(cust_id);
    }

    @ResponseBody
    @RequestMapping(value = "/findById", produces = {"application/json;charset=UTF-8;"})
    public String findById(int cust_id) throws JsonProcessingException {
        return mapper.writeValueAsString(service.findById(cust_id));
    }

    @ResponseBody
    @RequestMapping("/update")
    public String update(Customer customer){
        return service.update(customer);
    }
}
